package com.whzykj.model;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import com.whzykj.common.DateUtil;
import com.whzykj.jfinal.TableBind;

@TableBind(name = "log_login_status", pk = "login_id")
public class LogLoginStatus extends Model<LogLoginStatus>{
	private static final long serialVersionUID = 1L;
	public static final LogLoginStatus dao = new LogLoginStatus();
	
	/**
	 * APP用户登录登出时记录日志。首先，更改用户在线的状态；其次，将登录流水记录到登录日志表中。
	 * @param userinfo
	 * @param equipid
	 * @param equipkind
	 */
	public void log(Record userinfo,String equipid,String equipkind,String remarks,int loginKind){
		try{
			int userid=userinfo.getInt("USERID");
			LogLoginStatus loginStatus=LogLoginStatus.dao.findFirst("select * from log_login_status where USER_ID=?",userid);
			if(loginStatus==null){
				loginStatus=new LogLoginStatus();
				loginStatus.set("USER_ID", userid);
				loginStatus.set("LOGIN_STATUS", loginKind);
				loginStatus.set("LOGIN_TIME", DateUtil.getNow());
				loginStatus.set("LOGIN_EQUIP", equipkind);
				loginStatus.set("LOGIN_IP", equipid);
				loginStatus.set("REMARKS", remarks);
				loginStatus.set("CREATE_TIME", DateUtil.getNow());	// 首次登录时间
				loginStatus.save();	// 新增用户在线记录
			}else{
				loginStatus.set("LOGIN_STATUS", loginKind);
				if(loginKind==1){
					loginStatus.set("LOGIN_TIME", DateUtil.getNow());
				}else{
					loginStatus.set("LOGOUT_TIME", DateUtil.getNow());
				}
				loginStatus.set("LOGIN_EQUIP", equipkind);
				loginStatus.set("LOGIN_IP", equipid);
				loginStatus.set("REMARKS", remarks);
				loginStatus.update();	// 更新用户在线记录
			}
			LogLoginRecord record=new LogLoginRecord();
			record.set("USER_ID", userid);
			record.set("LOGIN_KIND", loginKind);	// 1:表示登录操作
			record.set("LOGIN_EQUIP", equipkind);
			record.set("LOGIN_IP", equipid);
			record.set("CREATE_TIME", DateUtil.getNow());
			record.set("REMARKS",remarks);
			record.save();			// 新增登录流水记录
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
}
